package MySql;

import java.sql.*;

import static MySql.MySqlStart.*;


/**
 * @author YZM
 * @date 2023/12/09
 */

public class MysqlOperate {
    static {
        //加载驱动
        try {
            Class.forName(JDBC_DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConn() throws SQLException {
        //创建连接对象
        Connection conn = DriverManager.getConnection(USER_DB_URL,name,pwd);
        return conn;
    }
    public static void closeall(ResultSet rs, PreparedStatement ps, Connection conn,Statement stmt) throws SQLException {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param sql
     * @param params
     * @return int
     * @throws SQLException
     */
    public static int MySql_Operate(String sql, Object[] params) throws SQLException {
        int count = 0;
        Connection conn = null;
        //准备SQL
        PreparedStatement ps = null;
        try {
            conn = MysqlOperate.getConn();
            ps = (PreparedStatement) conn.prepareStatement(sql);
            System.out.println("数据库存入操作：" + sql);
            if (params!=null)
            {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            count = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            MysqlOperate.closeall(null, ps, conn,null);
        }
        return count;
    }
    public static boolean MySQL_Command(String sql) throws SQLException {
        boolean pass=false;
        Connection conn = null;
        Statement stmt = null;
        try {
            //注册jdbc驱动
            conn = MysqlOperate.getConn();
            stmt = conn.createStatement();
            System.out.println("数据库操作：" + sql);
            Mysql_CommandState(stmt,sql);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            MysqlOperate.closeall(null, null, conn,stmt);
        }
        return true;
    }
    public static void Mysql_CommandState(Statement stmt, String SQLCode) {
        try {
            if (stmt.execute(SQLCode)==true) {
                System.out.println("\n########数据库操作成功:########\n" + SQLCode.toString());
            } else {
                System.out.println("\n########数据库操作失败:########\n" + SQLCode.toString());
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}